package com.umeox.iqibla.qimi_app

import com.umeox.moto.common.utils.DateUtils
import com.umeox.watch.moto.apiclient.model.AgentAppConfigDTO
import com.umeox.watch.moto.apiclient.model.AgentUsedRecord
import com.umeox.watch.moto.dataservice.DataProvider
import com.umeox.watch.moto.dataservice.proxy.PushApiClientProxy
import java.util.Date

object QiHelper {

    private var availableTimes = 0

    fun getAppKey() = BuildConfig.APPKEY

    fun getAgentIdByIndex(index: Int): String {
        return if (index == 0) {
            BuildConfig.BOY_AGENT_ID
        } else {
            BuildConfig.GRIL_AGENT_ID
        }
    }

    fun initAvailableTimes() {
        try {
            val result = getAgentAppConfig()
            availableTimes = result.limit - result.used
        } catch (e: Exception) {
            e.printStackTrace()
            availableTimes = -1
        }
    }

    fun getAvailableTimes(): Int {
        return availableTimes
    }


    fun usageStatistics(agentId: String) {
        availableTimes--

        submitAgentUsedRecord(AgentUsedRecord().apply {
            this.agentId = agentId
            usedTime = DateUtils.SDF_YMDHMS.format(Date())
            amount = 1
        })
    }


    private fun getAgentAppConfig(): AgentAppConfigDTO {
        val appKey = getAppKey()
        val userId = DataProvider.getHolderId()
        return PushApiClientProxy.fetchBinder().getAgentAppConfig(appKey, userId, 1)
    }

    private fun submitAgentUsedRecord(details: AgentUsedRecord) {
        val appKey = getAppKey()
        val userId = DataProvider.getHolderId()
        PushApiClientProxy.fetchBinder().submitAgentUsedRecord(appKey, userId, listOf(details))
    }


}